<?php
namespace Modules\Shop\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Shop\Entities\Article;
use Modules\Shop\Entities\Category;
use Modules\Shop\Entities\TagArticle;
use Modules\Shop\Http\Requests\ArticleRequest;
use Modules\Shop\Entities\Tag;
class ArticleController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Article::paginate(10);
        return view('shop::article.index', compact('data'));
    }

    //创建视图
    public function create(Article $article)
    {
    	$cates=Category::getCategory ();
    	if(!$cates){
    		session()->flash('danger','还未创建分类，先去创建吧');
    		return redirect ('shop/category');
		}
		$tags=Tag::get();
    	if(!($tags->toArray())){
			session()->flash('danger','还未创建标签，先去创建吧');
			return redirect ('shop/tag');
		}
        return view('shop::article.create',compact('article','cates','tags'));
    }

    //保存数据
    public function store(ArticleRequest $request,Article $article)
    {
        $article->fill($request->all());
        //dd($request['tag']);
        $article->save();
		foreach($request['tag'] as $v){
			TagArticle::create([
				'tag_id'=>$v,
				'article_id'=>$article['id']
			]);
		}
        return redirect('/shop/article')->with('success', '保存成功');
    }

    //显示记录
    public function show(Article $field)
    {
        return view('shop::article.show', compact('field'));
    }

    //编辑视图
    public function edit(Article $article)
    {
		$cates=Category::getCategory ();
		$tags=Tag::get();
		$t=[];
		foreach($article->tag as $v){
			$t[]=$v['tag_id'];
		}
        return view('shop::article.edit', compact('article','cates','tags','t'));
    }

    //更新数据
    public function update(ArticleRequest $request, Article $article)
    {
        $article->update($request->all());
        return redirect('/shop/article')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Article $article)
    {

        $article->delete();
        //删除文章的同时，将文章的标签中间表的数据也同时删除
		TagArticle::where('article_id',$article['id'])->delete();
        return redirect('shop/article')->with('success','删除成功');
    }
}
